# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/9/19 09:09
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : watershed_img_segmentation_based_on_gradient.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""
import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage import morphology,filters
from skimage.io import imread
image = imread("./../BoneXRayPic/m-1.0-0.5.png")[:,:,1]
denoised = filters.rank.median(image, morphology.disk(2))  # 过滤噪声

# 将梯度值低于10的作为开始标记点
markers = filters.rank.gradient(denoised, morphology.disk(5)) < 10
markers = ndi.label(markers)[0]

gradient = filters.rank.gradient(denoised, morphology.disk(2))  # 计算梯度
labels = morphology.watershed(gradient, markers, mask=image)  # 基于梯度的分水岭算法

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(6, 6))
axes = axes.ravel()
ax0, ax1 = axes

ax0.imshow(image, cmap="gray", interpolation='bilinear')
ax0.set_title("Original")
ax1.imshow(gradient, cmap="spectral", interpolation='bilinear')
ax1.set_title("Gradient")

for ax in axes:
    ax.axis('off')

fig.tight_layout()
plt.show()
